package com.bobo.web.provider.controller.wechat;

import com.bobo.web.api.domain.wxUser.WxUser;
import com.bobo.web.api.vo.base.ResponseResult;
import com.bobo.web.api.vo.user.WechatUserinfo;
import com.bobo.web.provider.service.UserService;
import com.bobo.web.provider.util.commutils.JacksonUtils;
import com.bobo.web.provider.util.wxUtils.WeChatAccessToken;
import com.bobo.web.provider.util.wxUtils.WeChatUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@RestController
@RequestMapping("/wechat")
public class WeChatController {
    private static Logger LOGGER = LoggerFactory.getLogger(WeChatController.class.getSimpleName());

    @Value("${basketball.wechat.appid}")
    private String wxappid;
    @Value("${basketball.wechat.secret}")
    private String wxsecret;
    @Value("${basketball.isTest}")
    private Boolean isTest;
    @Resource
    private UserService userService;
    @Resource
    private JacksonUtils jacksonUtils;
    /**
     * 获取微信用户标识OPENID
     *
     * @param request
     * @param response
     * @param code
     * @return
     */
    @RequestMapping(value = "/getOpenId")
    public ResponseResult<String> oauth2MeUrl(HttpServletRequest request, HttpServletResponse response, @RequestParam String code) {
        try {
            //通过code获取微信用户openid 存储在cookie中并返回给前端，之后前端每一次请求都需要把openid带过来。
            LOGGER.info("开始获取用户openID，code=" + code);
            WeChatAccessToken returnToken = WeChatUtils.getAccessToken(code, wxappid, wxsecret);
            if (returnToken != null && StringUtils.isNotEmpty(returnToken.getOpenid())) {
                String openId = returnToken.getOpenid();
                Cookie userCookie = new Cookie("openId", openId);
                userCookie.setMaxAge(-1);
                userCookie.setPath("/");
                response.addCookie(userCookie);
                LOGGER.info("渠道需要获取用户头像，开始获取用户头像信息");
                WechatUserinfo wxUserInfo = WeChatUtils.getWXUserInfoUrl(openId, returnToken.getAccess_token());
                LOGGER.info(jacksonUtils.toJson(wxUserInfo));
                //保存用户信息
                WxUser record = new WxUser();
                record.setHeadimgurl(wxUserInfo.getHeadimgurl());
                record.setCity(wxUserInfo.getCity());
                record.setNickName(wxUserInfo.getNickname());
                record.setOpenId(openId);
                record.setProvince(wxUserInfo.getProvince());
                record.setSex(wxUserInfo.getSex());
                userService.insertWxUserSelective(record);
            } else {
                return ResponseResult.error("Code不合法");
            }
        } catch (Exception e) {
            LOGGER.error("获取openId异常", e);
            return ResponseResult.error("获取openID异常");
        }
        return ResponseResult.success("获取openID成功");
    }

    /**
     *
     * @return
     */
    @RequestMapping(value = "/getTest")
    public ResponseResult<String> test() {
        WxUser dyWxUser = new WxUser();
        dyWxUser.setCity("2");
        userService.insertWxUserSelective(dyWxUser);
        return ResponseResult.success("获取openID成功");
    }


}
